package com.yirui.serialcomm;


import com.fazecast.jSerialComm.SerialPort;
import com.yirui.serialcomm.client.NetworkToSerialComm;
import com.yirui.serialcomm.core.util.Platform;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@Slf4j
public class ClientApplication implements ApplicationRunner {

    @Autowired
    private NetworkToSerialComm networkToSerialComm;

    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        //查看当前系统支持串口列表
        if(args.containsOption("ports")){
            log.info("###############################################");
            log.info("序号 |  名称   |   描述   |   位置");
            // 获取可用串口
            SerialPort[] ports = SerialPort.getCommPorts();
            int i = 1;
            for (SerialPort port : ports) {
                log.info("  {} | {} | {} | {}",i++, port.getSystemPortName(), port.getDescriptivePortName(),port.getPortLocation());
            }
            log.info("###############################################");
            System.exit(0);
        }else {
            //UNIX默认ttyS0,WIN默认COM2
            String commPort =  (Platform.isUnix() ? "ttyS0":"COM2");
            if(args.containsOption("serial-port")){
                commPort = args.getOptionValues("serial-port").get(0);
            }
            //串口:serial-port 与tcp/udp端口关联，把tcp与udp收到的数据通过串口传输

            int tcpPort = 10000;
            if(args.containsOption("tcp-port")){
                tcpPort =  Integer.parseInt(args.getOptionValues("tcp-port").get(0));
            }
            int udpPort = 12018;
            if(args.containsOption("udp-port")){
                udpPort = Integer.parseInt(args.getOptionValues("udp-port").get(0));
            }
            networkToSerialComm.start(tcpPort,udpPort, commPort);
        }

    }



}
